package cn.maxhou.service.impl;// 导入StringUtils用于获取文件后缀名
import cn.maxhou.service.UploadService;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service("toLocalUploadService") // 给bean命名
public class ToLocalUploadServiceImpl implements UploadService {
 
    private static final Logger LOGGER = LoggerFactory.getLogger(ToLocalUploadServiceImpl.class);
 
    /* 上传文件的保存目录 */
    public static final String UPLOAD_PATH = "/static/upload/";
 
    @Autowired
    private HttpServletRequest request; // 注入request主要为了获取本地路径
 
    @Override
    public String uploadFile(MultipartFile uploadFile, String... allowFileExtends) throws Exception {
        Set<String> include = new HashSet(Arrays.asList(allowFileExtends));
        // 获取保存路径
        String rootPath = request.getServletContext().getRealPath(UPLOAD_PATH);
        // 如果文件非空说明上传了文件数据
        if (!uploadFile.isEmpty()) {
            String fileName = uploadFile.getOriginalFilename();
            // 获得上传文件的扩展名
            String extension = StringUtils.getFilenameExtension(fileName);
            // 如果不包含扩展名
            if (!include.contains(extension)) {
                throw new Exception("上传文件仅支持" + include + "扩展名！");
            }
            String uploadFileName = UUID.randomUUID() + "." + extension;
            File file = new File(rootPath, uploadFileName);
            // 父目录不存在是无法保存的
            if (!file.getParentFile().exists()) {
                // 创建父目录
                file.getParentFile().mkdirs();
            }
            try {
                // 将上传的文件保存到本地路径
                uploadFile.transferTo(file);
                // 返回文件路径
                return UPLOAD_PATH + uploadFileName;
            } catch (Exception e) {
                LOGGER.error("执行ToLocalUploadServiceImpl" + ".uploadFile(MultipartFile, String[])出现错误.", e);
                throw e;
            }
        }
        return null;
    }
}